import {
    request,
    summary,
    query,
    description,
    tagsAll
} from 'koa-swagger-decorator';
import Joi from 'joi';
import Poppeteer from '../../service/puppeteer-pool';
const poppeteerInstance = Poppeteer.getInstance()

const screenShotSchema = {
    url: { type: 'string', required: true, description: '裁剪图片地址', validator: Joi.string().pattern(new RegExp('^http(s)?:\/\/.+')) },
    width: { type: 'number', description: '裁剪视图宽度', default: 375, validator: Joi.number() },
    height: { type: 'number', description: '裁剪视图高度', default: 577, validator: Joi.number() },
    encoding: { type: 'string', description: '生成图片类型，base64', validator: Joi.valid('base64') },
    waitTimeout: { type: 'number', description: '超时时间，等待window._puppeteerRenderDone属性为true的状态', default: 5000, validator: Joi.number() },
    selector: { type: 'string', description: '获取网页某个节点选择器，类或ID，有此选项则对改节点下面的dom进行截图', validator: Joi.string() }
};

function generatorJoi(source) {
    const schema = {}
    Object.keys(source).forEach(item => {
        if (source[item].validator) {
            schema[item] = source[item].validator
        }
    })
    return schema
}

const joiScreenShotSchema = Joi.object(generatorJoi(screenShotSchema))

@tagsAll('PuppeteerRouter')
export default class PuppeteerRouter {
    @request('GET', '/screenShot')
    @summary('puppeteer服务端截屏')
    @description('puppeteer截屏服务')
    @query(screenShotSchema)
    static async screenShot(ctx) {
        await joiScreenShotSchema.validateAsync(ctx.validatedQuery)
        const params = ctx.validatedQuery
        const img = await poppeteerInstance.screenshot(params)
        ctx.body = ctx.validatedQuery.encoding
            ? img.startsWith('error')
                ? img
                : `data:image/png;base64,${img}`
            : img
    }
}